package com.ruiyi.careryun.service.ota.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ruiyi.careryun.beans.VersionAndroid;
import com.ruiyi.careryun.beans.common.ResultMsg;
import com.ruiyi.careryun.mapper.ota.VersionAndroidMapper;
import com.ruiyi.careryun.service.ota.VersionAndroidService;

import io.sigpipe.jbsdiff.Diff;

@Service
public class VersionAndroidServiceImpl implements VersionAndroidService {
    // @Value("${ota.android.originalpath}")
    // private String originalPath;
    // @Value("${ota.android.patchfile}")
    // private String patchFile;
    // @Value("${ota.android.newapkpath}")
    // private String newApkPath;
    @Autowired
    private Environment env;
    @Autowired
    private VersionAndroidMapper versionAndroidMapper;

    @Override
    public ResultMsg<Map<String, Object>> updatePackage(String newVersion, MultipartFile file, Integer type) throws Exception {
        List<String> versionList = versionAndroidMapper.getAllVersionByType(type);
        if (versionList.contains(newVersion)) {
            return ResultMsg.error("此版本号已存在");
        }
        // 如果旧版号与新版本号不同且不为null或""或0,
        String[] path = new String[] { "/fm", "/va", "/adr", "/m", "/cey", "/ad" };
        if (versionList.size() > 0) {
            String lastVersion = versionList.get(versionList.size() - 1);
            if (!lastVersion.equals(newVersion)) {
                if (uploadFile(newVersion, file, type)) {
                    FileInputStream in = null;
                    OutputStream out = null;
                    // 生成差分包
                    in = new FileInputStream(new File(env.getProperty("ota.android.originalpath") + path[type - 1] + "/" + lastVersion + "/" + "update.apk"));
                    byte[] oldData = new byte[in.available()];
                    in.read(oldData);
                    in.close();
                    in = new FileInputStream(new File(env.getProperty("ota.android.originalpath") + path[type - 1] + "/" + newVersion + "/" + "update.apk"));
                    byte[] newData = new byte[in.available()];
                    in.read(newData);
                    in.close();
                    out = new FileOutputStream(new File(env.getProperty("ota.android.originalpath") + path[type - 1] + "/" + lastVersion + "/" + "update.patch"));
                    Diff.diff(oldData, newData, out);
                    System.err.println("差分完成");

                    versionAndroidMapper.add(new VersionAndroid(newVersion, type));
                    return ResultMsg.success();
                } else {
                    return ResultMsg.error("文件上传失败");
                }
            } else {
                return ResultMsg.error("版本号与旧版本号相同...");
            }
        } else {
            if (uploadFile(newVersion, file, type)) {
                versionAndroidMapper.add(new VersionAndroid(newVersion, type));
                return ResultMsg.success();
            } else {
                return ResultMsg.error("文件上传失败");
            }
        }
    }

    private Boolean uploadFile(String newVersion, MultipartFile file, Integer type) {
        String[] path = new String[] { "/fm", "/va", "/adr", "/m", "/cey", "/ad" };
        // 上传文件
        File targetFile = new File(env.getProperty("ota.android.originalpath") + path[type - 1] + "/" + newVersion, "update.apk");
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public Integer getVersionDiffCount(String androidVersion, Integer type) {
        return versionAndroidMapper.getVersionDiffCount(androidVersion, type);
    }

}
